<?php
class func{
function check_level($id){
	global $conf,$DB;
	if (!isset($cached['user']['user_'.$id]['level'])) {
		$r = $DB->fetch_row($DB->query("SELECT u_level FROM ".$conf['prefix']."user WHERE u_id = '".$id."'"));
		if ($r['u_level'] == 1 || $r['u_level'] == 2) $cached['user']['user_'.$id]['level'] = $r['u_level'];
		else $cached['user']['user_'.$id]['level'] = false;
	}
	return $cached['user']['user_'.$id]['level'];
	echo "ok";
}

function user_level($id) {
	global $DB, $conf,$lang;
	$qr=$DB->query("SELECT u_level FROM ".$conf['prefix']."user WHERE u_id ={$id}");
	$r = $DB->fetch_row($qr);
	switch ($r['u_level']) {
		case 1 : $level = $lang['admin'];	break;
		case 2 : $level = $lang['moderator'];	break;
		case 3 : $level = $lang['member'];	break;
	}
	return $level;
}


function check_email($email) {
	if (strlen($email) == 0) return false;
	if (eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $email)) return true;
	return false;
}

function checkLogin(){
	global $DB, $conf;
	$time_exit = NOW;
	$DB->query("UPDATE ".$conf['prefix']."user SET u_lastvisit = u_timeout, u_identifier = '', u_timeout = '', u_ip = '', u_online = 0 WHERE u_timeout < ".$time_exit." AND u_timeout > 0");
	
	if (!empty($_COOKIE['C_USER'])) {
		$identifier = $_COOKIE['C_USER'];
		$q = $DB->query("SELECT u_identifier, u_id FROM ".$conf['prefix']."user WHERE u_online = 1 AND u_ip = '".IP."' AND u_identifier = '".$identifier."'");
		if ($DB->num_rows($q)) {
			$r = $DB->fetch_row($q);
			$_SESSION['ses_user_id'] = $r['u_id'];
			$DB->query("UPDATE ".$conf['prefix']."user SET u_timeout = ".(NOW + 2*60*60)." WHERE u_id = '".$_SESSION['ses_user_id']."'");
			$return = true;
		}
		else $return = false;
	}
	else $return = false;

	if ($return == false)
		unset($_SESSION['ses_user_id']);
	return $return;
}
function random_str($len = 5) {
	$s = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	mt_srand ((double)microtime() * 1000000);
	$unique_id = '';
	for ($i=0;$i< $len;$i++)
		$unique_id .= substr($s, (mt_rand()%(strlen($s))), 1);
	return $unique_id;
}
function check_random_str($str,$len = 5) {
	if (!ereg('^([A-Za-z0-9]){'.$len.'}$',$str)) return false;
	return true;
}

function unhtmlchars($str) {
	return str_replace(array('&lt;', '&gt;', '&quot;', '&amp;', '&#92;', '&#39'), array('<', '>', '"', '&', chr(92), chr(39)), $str);
}

function htmlspecialchars_decrypt($string, $quote_style = ENT_COMPAT) {
    return strtr($string, array_flip(get_html_translation_table(HTML_SPECIALCHARS, $quote_style)));
}


function htmlchars($str) {
	return str_replace(
		array('&', '<', '>', '"', chr(92), chr(39)),
		array('&amp;', '&lt;', '&gt;', '&quot;', '&#92;', '&#39'),
		$str
	);
}

function utf8_to_ascii($str) {
$chars = array(
	'a'	=>	array('ấ','ầ','ẩ','ẫ','ậ','Ấ','Ầ','Ẩ','Ẫ','Ậ','ắ','ằ','ẳ','ẵ','ặ','Ắ','Ằ','Ẳ','Ẵ','Ặ','á','à','ả','ã','ạ','â','ă','Á','À','Ả','Ã','Ạ','Â','Ă'),
	'e' =>	array('ế','ề','ể','ễ','ệ','Ế','Ề','Ể','Ễ','Ệ','é','è','ẻ','ẽ','ẹ','ê','É','È','Ẻ','Ẽ','Ẹ','Ê'),
	'i'	=>	array('í','ì','ỉ','ĩ','ị','Í','Ì','Ỉ','Ĩ','Ị'),
	'o'	=>	array('ố','ồ','ổ','ỗ','ộ','Ố','Ồ','Ổ','Ô','Ộ','ớ','ờ','ở','ỡ','ợ','Ớ','Ờ','Ở','Ỡ','Ợ','ó','ò','ỏ','õ','ọ','ô','ơ','Ó','Ò','Ỏ','Õ','Ọ','Ô','Ơ'),
	'u'	=>	array('ứ','ừ','ử','ữ','ự','Ứ','Ừ','Ử','Ữ','Ự','ú','ù','ủ','ũ','ụ','ư','Ú','Ù','Ủ','Ũ','Ụ','Ư'),
	'y'	=>	array('ý','ỳ','ỷ','ỹ','ỵ','Ý','Ỳ','Ỷ','Ỹ','Ỵ'),
	'd'	=>	array('đ','Đ'),
	''	=>  array('\'','"'),
);
foreach ($chars as $key => $arr) 
	foreach ($arr as $val)
		$str = str_replace($val,$key,$str);
return $str;
}

function get_ext($url){
	$ext = explode('.',$url);
	$ext = $ext[count($ext)-1];
	$ext = explode('?',$ext);
	$ext = $ext[0];
	return $ext;
}

function title_2_ascii($title,$t=false){
$title=$this->unhtmlchars($title);
	if($t)
	$title=$this->utf8_to_ascii($title);
	$title=strtolower($title);
	$chars = array(
			''	=>	array('<','>','"','\'','?','(',')','!','_','-','@','$','%','^','{','}','.',','),
			'_' =>	array('&',',',' ',':'),
			
	);
		foreach ($chars as $key => $arr) 
			foreach ($arr as $val)
				$title = str_replace($val,$key,$title);
		return $title;	
}

function change_link($type,$id='',$name='',$p=''){
	global $conf;

	switch($type){
	case "main" 		: 
		if($p) $link=$conf['web_url']."/?act=main&sub=".$id."&p=".$p;
		else  $link=$conf['web_url']."/?act=main&sub=".$id;
		break;
	case "search" 		: 
		if($p) $link=$conf['web_url']."/?act=search&id=".$id."&p=".$p."&keyword=".$name;
		else  $link=$conf['web_url']."/?act=search&id=".$id."&keyword=".$name;
		break;
	case "cat" 		: 
		if($p) $link=$conf['web_url']."/?act=cat&id=".$id."&p=".$p;
		else  $link=$conf['web_url']."/?act=cat&id=".$id;
		break;
	case "song" 	: $link=$conf['web_url']."/?act=song&id=".$id; break;
	case "album"	:
		if($p) $link=$conf['web_url']."/?act=album&id=".$id."&p=".$p;
		else  $link=$conf['web_url']."/?act=album&id=".$id;
		break;
	case "movie"	: $link=$conf['web_url']."/?act=movie&id=".$id; break;	
	case "movie_epi"	: $link=$conf['web_url']."/?act=movie&id=".$id."&p=".$p; break;	
	case "moviefull"	: $link=$conf['web_url']."/?act=moviefull&id=".$id; break;	
	case "playlist"	: $link=$conf['web_url']."/?act=playlist&id=".$id; break;	
	case "singer"	:
		if($p) $link=$conf['web_url']."/?act=singer&id=".$id."&p=".$p;
		else  $link=$conf['web_url']."/?act=singer&id=".$id;
		break;
	case "user" 	:
		if($p) $link=$conf['web_url']."/?act=user&id=".$id."&p=".$p;
		else  $link=$conf['web_url']."/?act=user&id=".$id;
	break;	
	case "user_log" 	: $link=$conf['web_url']."/?act=user&sub=".$id; break;	
	case "do" 	: $link=$conf['web_url']."/?do=".$id; break;
	case "tivi" 	: $link=$conf['web_url']."/?act=tivi"; break;	
	case "register"	: $link=$conf['web_url']."/?act=register"; break;	
	case "add_playlist"	: $link=$conf['web_url']."/?act=playlist&sub=add"; break;		
	case "mtv"	: $link=$conf['web_url']."/?act=mtv"; break;				
	case "video"	: 
			if($p) $link=$conf['web_url']."/?act=video&p=".$p;
			else  $link=$conf['web_url']."/?act=video";
			break;
	case "video-detail"	: $link=$conf['web_url']."/?act=video-detail&id=".$id; break;		
	case "sms"	: $link=$conf['web_url']."/?act=sms"; break;	
	}

/*
	if(trim($name)=='') $name="360phim";
	switch($type){
		case "main" 		: 
		if($p) $link=$conf['web_url']."/?act=main&sub=".$id."&p=".$p;
		else  $link=$conf['web_url']."/?act=main&sub=".$id;
		break;
		case "search" 		: 
		if($p) $link=$conf['web_url']."/?act=search&id=".$id."&p=".$p."&keyword=".$name;
		else  $link=$conf['web_url']."/?act=search&id=".$id."&keyword=".$name;
		break;
		case "cat" 		: 
			if($p) $link=$conf['web_url']."/cat/".$id."/page/".$p."/".$name.".html";
			else  $link=$conf['web_url']."/cat/".$id."/".$name.".html";
			break;
		case "song" 	: $link=$conf['web_url']."/song/".$id."/".$name.".html"; break;
		case "album"	:
			if($p) $link=$conf['web_url']."/album/".$id."/page/".$p."/".$name.".html";
			else  $link=$conf['web_url']."/album/".$id."/".$name.".html";
			break;
		case "movie"	: $link=$conf['web_url']."/movie/".$id."/".$name.".html"; break;	
		case "moviefull"	: $link=$conf['web_url']."/moviefull/".$id."/".$name.".html"; break;	
		case "playlist"	: $link=$conf['web_url']."/playlist/".$id."/".$name.".html"; break;	
		case "singer"	:
			if($p) $link=$conf['web_url']."/singer/".$id."/page/".$p."/".$name.".html";
			else  $link=$conf['web_url']."/singer/".$id."/".$name.".html";
			break;
		case "user" 	:
			if($p) $link=$conf['web_url']."/user/".$id."/page/".$p."/".$name.".html";
			else  $link=$conf['web_url']."/user/".$id."/".$name.".html";
			break;	
		case "user_log" 	: $link=$conf['web_url']."/?act=user&sub=".$id; break;	
		case "tivi" 	: $link=$conf['web_url']."/tivi/".$name.".html"; break;	
		case "do" 	: $link=$conf['web_url']."/?do=".$id; break;
		case "register"	: $link=$conf['web_url']."/register/".$name.".html"; break;	
		case "add_playlist"	: $link=$conf['web_url']."/playlist/add/".$name.".html"; break;	
		case "mtv"	: $link=$conf['web_url']."/mtv/".$name.".html"; break;		
		case "video"	: 
			if($p) $link=$conf['web_url']."/video/page/".$p."/".$name.".html";
			else  $link=$conf['web_url']."/video/".$name.".html";
			break;
		case "video-detail"	: $link=$conf['web_url']."/video-detail/".$id."/".$name.".html"; break;				
	}
*/
	return $link;

}

function text_2_html($txt = "", $htmlchars = false) {
	if ($htmlchars) $txt = htmlspecialchars($txt);
	$txt = str_replace("\n","<br />",$txt);
	$txt = str_replace("\t","&nbsp;&nbsp;",$txt);
	//$txt = preg_replace( "/\\n/"    , "<br />"           , $txt );
	$txt = preg_replace( "/  /" , " &nbsp;"      , $txt );
	$search = array('@<script[^>]*?>.*?</script>@si', // Strip out javascript
	'@<style[^>]*?>.*?</style>@siU', // Strip style tags properly
	'@<[\/\!]*?[^<>]*?>@si', // Strip out HTML tags
	'@<![\s\S]*?--[ \t\n\r]*>@', // Strip multi-line comments including CDATA
	'@<iframe[^>]*?>.*?</iframe>@si'
	);
	$txt = preg_replace($search, '', $txt);
	return $txt;
}

function view_pages_ajax($ttrow,$n,$pg,$func_ajax,$show_all=true,$id=''){
		global $lang,$func;
		$total = ceil($ttrow/$n);
		if ($total <= 1) return '';
		$v_f = 3;
		$v_a = 2;
		$v_l = 3;
		$max_pages = $v_f + $v_a + $v_l + 5;
		$z_1 = $z_2 = $z_3 = false;		
		if($id)
			$ajax=$func_ajax.$id.",";
		else
			$ajax=$func_ajax;
		$block = '<div class="pager" align="center"><span>';
		$pgt = $pg-1;
		if ($pg != 1){
			$block .= '<a class=command onClick="'.$ajax.'\'\');return false;" href="#"  title ="'.$lang['first_page'].'"><b>&laquo;&laquo;</b></a>';
	if($show_all)
			$block .='<a class=command onClick="'.$ajax.$pgt.');return false;" href="#"  title="'.$lang['pre_page'].'"><b>&laquo;</b></a>';		
		}
	if($show_all){
		for($m = 1; $m <= $total; $m++) {
			if ($total > $max_pages) {
				if (($m > $v_f) && (($m < $pg - $v_a) || ($m > $pg + $v_a)) && ($m < $total - $v_l + 1)) {
					if (!$z_1 && ($m > $v_f)) {
						$block .= "...";
						$z_1 = true;
					}
					elseif (!$z_2 && ($m > $pg + $v_a)) {
						$block .= "...";
						$z_2 = true;
					}
					continue;
				}
			}	
			if($m == $pg)
				$block .='<span class="current">'.$m.'</span>';
			else
				$block .= '<a  onClick="'.$ajax.$m.');return false;" href="#" title="'.$lang['view'].' '.$m.'" class=command>'.$m.'</a>';
		}
	}
		$pgs = $pg + 1;
		if($show_all){
		if ($pg != $total)
			$block .= '<a class=command onClick="'.$ajax.$pgs.');return false;" href="#"  title="'.$lang['next_page'].'"><b>&raquo;</b></a><a class=command onClick="'.$ajax.$total.');return false;" href="#"  title="'.$lang['end_page'].'"><b>&raquo;&raquo;</b></a>' ;
		}
		$block.='</span></div>';	
		return $block;
	}

function getwords($str,$num)
{
	$limit = $num - 1 ;
    $str_tmp = '';
    $arrstr = explode(" ", $str);
    if ( count($arrstr) <= $num )  return $str;
    if (!empty($arrstr))
    {
        for ( $j=0; $j< count($arrstr) ; $j++)    
        {
            $str_tmp .= " " . $arrstr[$j];
            if ($j == $limit) 
                break;
        }
    }
    return $str_tmp.'...';
}

function makedatetime($text) {
	   $parse=explode(" ",$text);
	   $tmp = explode ("-",$parse[0]);
	   return $tmp[2]."/".$tmp[1]."/".$tmp[0]." ".$parse[1];
}

function get_img($type,$id,$full=false) {
	global $DB,$conf;
	if ($type == 'multimedia') {
		$r=$DB->query("SELECT multi_img,multi_local_img,multi_type FROM {$conf['prefix']}multimedia WHERE multi_id={$id}");
		$j=$DB->fetch_row($r);
		if($j['multi_type']==1){
			$dir=$conf['album_img'];
			$dir_thumb=$conf['album_thumb'];
		}elseif($j['multi_type']==2){
			$dir=$conf['root_img'];
			$dir_thumb=$conf['img_thumb'];
		}
		if(!empty($dir) && !empty($j['multi_local_img']) && $full)
			$img = $conf['web_url']."/".$dir."/".$j['multi_local_img'];
		elseif(!empty($dir_thumb)&& !empty($j['multi_local_img']))
			$img = $conf['web_url']."/".$dir_thumb."/".$j['multi_local_img'];
		else
			$img=$this->unhtmlchars($j['multi_img']);
		if (!$img) $img = "{TPL_LINK}/img/no_album.gif";
	}

	elseif ($type == 'singer') {
		$r=$DB->query("SELECT singer_img,singer_local_img FROM {$conf['prefix']}singer WHERE singer_id={$id}");
		$j=$DB->fetch_row($r);
		$dir=$conf['singer_img'];
		if(!empty($dir) && !empty($j['singer_local_img']))
			$img = $conf['web_url']."/".$dir."/".$j['singer_local_img'];
		else
			$img=$this->unhtmlchars($j['singer_img']);
		if (!$img) $img = "{TPL_LINK}/img/no_singer.gif";
	}
	
	elseif ($type == 'playlist') {
		$r=$DB->query("SELECT pl_img FROM {$conf['prefix']}playlist WHERE pl_id={$id}");
		$j=$DB->fetch_row($r);
		$dir=$conf['dir_imgpl'];
		if(!empty($dir) && !empty($j['pl_img']))
			$img = $conf['web_url']."/".$dir."/".$j['pl_img'];
			
		if (!$img) $img = "{TPL_LINK}/img/no_playlist.gif";
	}
	elseif ($type == 'avatar') {
		$r=$DB->query("SELECT u_avatar FROM {$conf['prefix']}user WHERE u_id={$id}");
		$j=$DB->fetch_row($r);
		$dir=$conf['dir_avatar'];
		if(!empty($dir) && !empty($j['u_avatar']))
			$img = $conf['web_url']."/".$dir."/".$j['u_avatar'];
			
		if (!$img) $img = "{TPL_LINK}/img/no_avatar.gif";
	}

	return $img;
}


function get_data($type,$v,$field = '') {
	global $DB, $conf, $cached,$lang;
	if ($type == 'cat') {
		if (!$field) $field = 'cat_name';
		if (!$cached['cat'][$v]) {
			$r = $DB->fetch_row($DB->query("SELECT ".$field." FROM ".$conf['prefix']."cat WHERE cat_id = '".$v."'"));
			$cached['cat'][$v] = $this->unhtmlchars($r[$field]);
		}
		return $cached['cat'][$v];
	}

	elseif ($type == 'playlist') {
		if (!$field) $field = 'pl_name';
		if (!$cached['playlist'][$v]) {
			$r = $DB->fetch_row($DB->query("SELECT ".$field." FROM ".$conf['prefix']."playlist WHERE pl_id = '".$v."'"));
			$cached['playlist'][$v] = $this->unhtmlchars($r[$field]);
		}
		return $cached['playlist'][$v];
	}
	elseif ($type == 'user') {
		if (!$field) $field = 'u_name';
		if (!$cached['user']['user_'.$v][$field]) {
			$r = $DB->fetch_row($DB->query("SELECT ".$field." FROM ".$conf['prefix']."user WHERE u_id = '".$v."'"));
			$cached['user']['user_'.$v][$field] = $this->unhtmlchars($r[$field]);
		}
		if ($field == 'u_hide_info') {
			$hide_list = array('hide_sex','hide_email');
			$len = count($hide_list);
			if ($this->check_level($_SESSION['ses_user_id']) == 1)
				$hide_info = '';
			else {
				$hide_info = $cached['user']['user_'.$v]['u_hide_info'];
				$hide_info = decbin($hide_info);
			}
			
			while (strlen($hide_info) < $len) $hide_info = '0'.$hide_info;
			for ($i=0;$i<$len;$i++) $arr[$hide_list[$i]] = $hide_info[$i];
			return $arr;
			
		}
		return $cached['user']['user_'.$v][$field];
	}
	elseif ($type == 'song') {
		if (!$field) $field = 'm_title';
		if (!$cached['song']['song_'.$v][$field]) {
			$r = $DB->fetch_row($DB->query("SELECT ".$field." FROM ".$conf['prefix']."media WHERE m_id = '".$v."'"));
			$cached['song']['song_'.$v][$field] = $this->unhtmlchars($r[$field]);
		}
		return $cached['song']['song_'.$v][$field];
	}
	elseif ($type == 'player') {
		if (!$field) $field = 'player_img';
		$dir_type="img/media/type/";
		if (!$cached['player']['player_'.$v][$field]) {
			$r = $DB->fetch_row($DB->query("SELECT ".$field." FROM ".$conf['prefix']."player WHERE player_id = '".$v."'"));
			$r[$field]=$dir_type.$r[$field];
			if($field == 'player_img' && $r[$field]=='')
				$r[$field]=$dir_type."unknown.gif";
			 	
			$cached['player']['player_'.$v][$field] = $this->unhtmlchars($r[$field]);
		}
		return $cached['player']['player_'.$v][$field];
	}
	elseif ($type == 'multimedia') {
		if (!$field) $field = 'multi_name';
		if (!$cached['multi']['multi_'.$v][$field]) {
			if ($v == 0 && $field == 'multi_name') return $lang['updating'];
			$r = $DB->fetch_row($DB->query("SELECT ".$field." FROM ".$conf['prefix']."multimedia WHERE multi_id = '".$v."'"));
			$cached['multi']['multi_'.$v][$field] = $this->unhtmlchars($r[$field]);
		}
		return $cached['multi']['multi_'.$v][$field];
	}
	elseif ($type == 'singer') {
		if (!$field) $field = 'singer_name';
		if ($field == 'singer_name') {
			$c_name =& $cached['singer']['singer_'.$v][$field];
			if (!$c_name) {
				if ($v == -1) $c_name = "Chưa biết (VN)";
				elseif ($v == -2) $c_name = "Chưa biết (QT)";
				//elseif ($v == -3) $c_name = "Chưa biết (Band)";
				else {
					$r = $DB->fetch_row($DB->query("SELECT ".$field." FROM ".$conf['prefix']."singer WHERE singer_id = '".$v."'"));
					$c_name = $this->unhtmlchars($r[$field]);
				}
			}
			return $c_name;
		}

		else {
			$r = $DB->fetch_row($DB->query("SELECT ".$field." FROM ".$conf['prefix']."singer WHERE singer_id = '".$v."'"));
			return $this->unhtmlchars($r[$field]);
		}
	}
}


function viewpages($ttrow,$n,$pg,$title=''){
		global $lang,$func,$cmd;
		$total = ceil($ttrow/$n);
		if ($total <= 1) return '';
		$v_f = 3;
		$v_a = 2;
		$v_l = 3;
		$max_pages = $v_f + $v_a + $v_l + 5;
		
		$z_1 = $z_2 = $z_3 = false;
		
		$block = '<div class="pager" align="center"><span>';
		$pgt = $pg-1;
		if ($pg != 1){
			$block .= '<a class=command href="'.$func->change_link($cmd[1],$cmd[2],$title).'"  title ="'.$lang['first_page'].'"><b>&laquo;&laquo;</b></a>';
			$block .='<a class=command href="'.$func->change_link($cmd[1],$cmd[2],$title,$pgt).'"  title="'.$lang['pre_page'].'"><b>&laquo;</b></a>';
		}
		for($m = 1; $m <= $total; $m++) {
			if ($total > $max_pages) {
				if (($m > $v_f) && (($m < $pg - $v_a) || ($m > $pg + $v_a)) && ($m < $total - $v_l + 1)) {
					if (!$z_1 && ($m > $v_f)) {
						$block .= "...";
						$z_1 = true;
					}
					elseif (!$z_2 && ($m > $pg + $v_a)) {
						$block .= "...";
						$z_2 = true;
					}
					continue;
				}
			}	
		
			if($m == $pg)
				$block .='<span class="current">'.$m.'</span>';
			else
				$block .= '<a href="'.$func->change_link($cmd[1],$cmd[2],$title,$m).'" title="'.$lang['view'].' '.$m.'" class=command>'.$m.'</a>';
		}	
		$pgs = $pg + 1;

		if ($pg != $total)
			$block .= '<a class=command href="'.$func->change_link($cmd[1],$cmd[2],$title,$pgs).'"  title="'.$lang['next_page'].'"><b>&raquo;</b></a><a class=command href="'.$func->change_link($cmd[1],$cmd[2],$title,$total).'"  title="'.$lang['end_page'].'"><b>&raquo;&raquo;</b></a>' ;
		$block.='</span></div>';
		return $block;
}


function check_rate($rate,$total_rate) {
	global $lang;
	if ($total_rate =='0') $current_star = 0;
	else $rater_rating = $rate;
	if ($rater_rating <= 0  ){$star1 = "none"; $star2 = "none"; $star3 = "none"; $star4 = "none"; $star5 = "none";}
	if ($rater_rating >= 0.5){$star1 = "half"; $star2 = "none"; $star3 = "none"; $star4 = "none"; $star5 = "none";}
	if ($rater_rating >= 1  ){$star1 = "full"; $star2 = "none"; $star3 = "none"; $star4 = "none"; $star5 = "none";}
	if ($rater_rating >= 1.5){$star1 = "full"; $star2 = "half"; $star3 = "none"; $star4 = "none"; $star5 = "none";}
	if ($rater_rating >= 2  ){$star1 = "full"; $star2 = "full"; $star3 = "none"; $star4 = "none"; $star5 = "none";}
	if ($rater_rating >= 2.5){$star1 = "full"; $star2 = "full"; $star3 = "half"; $star4 = "none"; $star5 = "none";}
	if ($rater_rating >= 3  ){$star1 = "full"; $star2 = "full"; $star3 = "full"; $star4 = "none"; $star5 = "none";}
	if ($rater_rating >= 3.5){$star1 = "full"; $star2 = "full"; $star3 = "full"; $star4 = "half"; $star5 = "none";}
	if ($rater_rating >= 4  ){$star1 = "full"; $star2 = "full"; $star3 = "full"; $star4 = "full"; $star5 = "none";}
	if ($rater_rating >= 4.5){$star1 = "full"; $star2 = "full"; $star3 = "full"; $star4 = "full"; $star5 = "half";}
	if ($rater_rating >= 5  ){$star1 = "full"; $star2 = "full"; $star3 = "full"; $star4 = "full"; $star5 = "full";}
	$rater_stars_img =     "<img src=\"{TPL_LINK}/img/rate/".$star1.".gif\" border=0>"
		."<img src=\"{TPL_LINK}/img/rate/".$star2.".gif\" border=0>"
		."<img src=\"{TPL_LINK}/img/rate/".$star3.".gif\" border=0>"
		."<img src=\"{TPL_LINK}/img/rate/".$star4.".gif\" border=0>"
		."<img src=\"{TPL_LINK}/img/rate/".$star5.".gif\" border=0>";
		if($total_rate>0)
		$rater_stars_img .=" ( ".$total_rate." ".$lang['num_rate']." )";
		else
		$rater_stars_img .="  {$lang['title_rate']}";
	return 	$rater_stars_img;
}

function md5_encrypt ( $plain_text, $password = PASSWORD, $iv_len = 16 ) {
    $plain_text .= "\x13";
    $n = strlen ( $plain_text );
    if ( $n % 16 ) $plain_text .= str_repeat ( "\0", 16 - ( $n % 16 ) );
    $i = 0;
    $enc_text = $this->get_rnd_iv ( $iv_len );
    $iv = substr ( $password ^ $enc_text, 0, 512 );
    while ( $i < $n ) {
        $block = substr ( $plain_text, $i, 16 ) ^ pack ( 'H*', md5 ( $iv ) );
        $enc_text .= $block;
        $iv = substr ( $block . $iv, 0, 512 ) ^ $password;
        $i += 16;
    }
    return base64_encode ( $enc_text );
}

function get_rnd_iv ( $iv_len ) {
    $iv = '';
    while ( $iv_len-- > 0 ) {
        $iv .= chr ( mt_rand ( ) & 0xFF );
    }
    return $iv;
}

function md5_decrypt ( $enc_text, $password = PASSWORD, $iv_len = 16 ) {
    $enc_text = base64_decode ( $enc_text );
    $n = strlen ( $enc_text );
    $i = $iv_len;
    $plain_text = '';
    $iv = substr ( $password ^ substr ( $enc_text, 0, $iv_len ), 0, 512 );
    while ( $i < $n ) {
        $block = substr ( $enc_text, $i, 16 );
        $plain_text .= $block ^ pack ( 'H*', md5 ( $iv ) );
        $iv = substr ( $block . $iv, 0, 512 ) ^ $password;
        $i += 16;
    }
    return preg_replace ( '/\\x13\\x00*$/', '', $plain_text );
}


function encode_down($id,$pass=PASSWORD) {
	$m = strtoupper(substr(md5($pass.$id),6,16));
	return 'RJ-'.$m;
}

function get_player($mid){	
		global $DB,$conf;	
  $repi=$DB->query("SELECT * FROM ".$conf['prefix']."media where m_id={$mid}");
  if($epi=$DB->fetch_row($repi)){
	  $re=$DB->query("SELECT * FROM ".$conf['prefix']."player where player_id={$epi['m_type']}");
	  $type=$DB->fetch_row($re);
	 if($type['player_use_xml'])  
		$url_file=$conf['web_url'].'/%3Fact=xml%26id='.$mid."%26type=1";
	 elseif($type['player_use_wpl'])  
		$url_file=$conf['web_url'].'/%3Fact=wpl%26id='.$mid."%26type=1"; 		
	 else
	  	$url_file=($type['player_isgrab'])?$this->grab_link($this->unhtmlchars($epi['m_url'])):$this->unhtmlchars($epi['m_url']);  
		$player=$this->unhtmlchars(stripslashes($type['player_html']));
		$player=str_replace("{WEB_URL}",$conf['web_url']."/",$player);
		$player=str_replace("{WIDTH}",$type['player_width'],$player);
		$player=str_replace("{HEIGHT}",$type['player_height'],$player);
		$player=str_replace("{URL}",$url_file,$player);
  }
	return $player;		  
}
function get_server($id,$data_url){
	global $conf;
			preg_match_all("#<server>(.*?)</server>#",$conf['data_server'],$r);
			if(count($r[0])){
					for($i=0;$i<=count($r[0])-1;$i++){
					$j=$i+1;
					preg_match("#<id>([0-9]+)</id>#",$r[1][$i],$match);
					preg_match("#<folder>(.*?)</folder>#",$r[1][$i],$match1);
					preg_match("#<host>(.*?)</host>#",$r[1][$i],$match2);
					if($match[1]==$ro_url['m_is_local'])
						$url=$match2[1]."/".$match1[1]."/".$data_url;
					}	
			}
		return $url;
}


function smiles_replace($s) {
	global $conf;
	$smiles_array=array(
	6 => '>:D<',		18 => '#:-S',				36 => '<:-P',		42 => ':-SS',
	48 => '<):)',		50 => '3:-O',				51 => ':(|)',		53 => '@};-',
	55 => '**==',		56 => '(~~)',				58 => '*-:)',		63 => '[-O<',
	67 => ':)>-',		77 => '^:)^',				106 => ':-??',		25 => array('O:)','O:-)'),
	26 => ':-B',		28 => 'I-)',				29 => '8-|',		30 => 'L-)',
	31 => ':-&',		32 => ':-$',				33 => '[-(',		34 => ':O)',
	35 => '8-}',		7 => ':-/',					37 => '(:|',		38 => '=P~',
	39 => ':-?',		40 => '#-O',				41 => '=D>',		9 => ':">',
	43 => '@-)',		44 => ':^O',				45 => ':-W',		46 => ':-<',
	47 => '>:P',		11 => array(':*',':-*'),	49 => ':@)',		12 => '=((',
	13 => ':-O',		52 => '~:>',				16 => 'B-)',		54 => '%%-',
	17 => ':-S',		5 => ';;)',					57 => '~O)',		19 => '>:)',
	59 => '8-X',		60 => '=:)',				61 => '>-)',		62 => ':-L',
	20 => ':((',		64 => '$-)',				65 => ':-"',		66 => 'B-(',
	21 => ':))',		68 => '[-X',				69 => '\:D/',		70 => '>:/',
	71 => ';))',		72 => 'O->',				73 => 'O=>',		74 => 'O-+',
	75 => '(%)',		76 => ':-@',				23 => '/:)',		78 => ':-J',
	79 => '(*)',		100 => ':)]',				101 => ':-C',		102 => '~X(',
	103 => ':-H',		104 => ':-T',				105 => '8->',		24 => '=))',
	107 => '%-(',		108 => ':O3',				1 => array(':)',':-)'),		2 => array(':(',':-('),
	3 => array(';)',';-)'),		22 => array(':|',':-|'),		14 => array('X(','X-('),		15 => array(':>',':->'),
	8 => array(':X',':-X'),		4 => array(':D',':-D'),		27 => '=;',		10 => array(':P',':-P'),
	);

foreach ($smiles_array as $a => $b) {
	$x = array();
	if (is_array($b)) {
		for ($i=0;$i<count($b);$i++) {
			$b[$i] = $b[$i];
			$x[] = $b[$i];
			$v = strtolower($b[$i]);
			if ($v != $b[$i]) $x[] = $v;

		}
	}
	else {

		$x[] = $b;
		$v = strtolower($b);
		if ($v != $b) $x[] = $v;

	}
	$p = '';
	for ($u=0;$u<strlen($x[0]);$u++) {
		$ord = ord($x[0][$u]);
		if ($ord < 65 && $ord > 90) $p .= '&#'.$ord.';';
		else $p .= $x[0][$u];
	}
	$s = str_replace($x,'<img src='.$conf['web_url'].'/images/smiley/'.$a.'.gif>',$s);
}
return $s;
}

	function grab_link($url,$direct=false){
		global $conf;
		if(preg_match('#tamtay\.vn\/video#',$url)){
			if(!preg_match('#play\/([0-9]+)#', $url ,$id_sr))
				preg_match('#play\/config\/([0-9]+)#', $url ,$id_sr);
				
			if(!$direct){
				$url="http://video.tamtay.vn/video/play/".$id_sr[1];
				/*
				$arr_host=array("http://mtvhaiduong.net/");
					$id_host=rand(0,count($arr_host)-1);
						$code=$this->get_by_curl($arr_host[$id_host]."java1.php?var=".urlencode($id_sr[1]));
						preg_match("#<daica>(.*?)</daica>#",$code,$url_tt);
						$url=$url_tt[1];
				*/
				/*
		$post_send="joy=1&link=".urlencode("http://video.tamtay.vn/video/play/".$id_sr[1]."/")."&vars=&head=1&foll=1&cook=";
				$data=$this->get_by_curl("http://luongvanchanh.vn/index(1).php",true,$post_send);
					//$data=$func->get_by_curl("http://video.tamtay.vn/video/play/".$id_sr[1]."/");
					preg_match("#SWFObject\(\"(.*?)\",#",$data,$flash);
					$refer="http://video.tamtay.vn".$flash[1];
					$video='';
					if(preg_match("#var v=new Array\(([0-9]+)\)\;#",$data)){
						preg_match_all("#v\[([0-9]+)\]=\"(.*?)\"\;#",$data,$v);
						for($i=0;$i<=count($v[0])-1;$i++)
							$video.=$v[2][$i];					
						
					}
					elseif(preg_match("#var v([0-9]+)=new Array\(([0-9]+)\)\;#",$data)){
					preg_match_all("#v([0-9]+)\[([0-9]+)\]=\"(.*?)\"\;#",$data,$v);
						for($i=0;$i<=count($v[0])-1;$i++)
							$video.=$v[3][$i];					
						
					}
					else{
						preg_match("#\{configFileName\: '(.*?)'\}#",$data,$r);
						preg_match_all("#\\+ \"(.*?)\"#",$r[1],$v);
						$video.=$v[1][0].$v[1][1];	
					}
				if($video!='')
				$url='http://video.tamtay.vn'.$video;
				else
				$url="http://video.tamtay.vn/video/play/config/".$var."/2";
				*/
			}
			else
				$url="http://video.tamtay.vn/video/play/config/".$id_sr[1]."/2";
					//$url="http://mono.mn/tt.php?id=".$id_sr[1];
				
				if(!$url)
					$url="http://video.tamtay.vn/video/play/config/".$id_sr[1]."/2";
			
		}

			$pat_zing='#http:\/\/video.zing.vn\/zv\/clip\/(.*?)\.html#';
			$pat_zing_1='#http:\/\/video.zing.vn\/video\/clip\/(.*?)\.html#';
			if((preg_match($pat_zing, $url)) || (preg_match($pat_zing_1, $url))){				
				if(preg_match($pat_zing, $url))
				$url=str_replace("/zv/clip","/video/clip",$url);
				//$code=$this->get_by_curl($url);		
				
				//preg_match("#xmlFile\:\"(.*?)\"#",$code,$sid);	
				$xml=$this->get_by_curl("http://mtvhaiduong.net/ser_grab.php?url=".$url);
					preg_match("#<solo>(.*?)</solo>#s",$xml, $dr);
					$url=trim($dr[1]);
				/*
				if($direct==false)
					$url=$sid[1];
				else{					
					$doc = new DOMDocument();
					@$doc->formatOutput = true;	
					$file_xml="http://video.zing.vn/getXML.php?request=chunk&vid=".$sid[1];
					@$doc->load($file_xml);
					$cur = @$doc->getElementsByTagName( "flvSource" );
					$url_file = $cur->item(0)->nodeValue;
					if(!$url_file || ($url_file && (preg_match('#404 Not Found#i',$this->get_head_curl($url_file,10))))){
						$cur_mp4 = @$doc->getElementsByTagName( "mp4Source" );
						$url_file = $cur_mp4->item(0)->nodeValue;
					}
					$url=$url_file;
				}
				*/
				/*
				preg_match("@openWindow\(['\"]http://video.zing.vn/player/flowplayer.php\?id\=(.*?)['\"],@",$code,$flow_id);
																									
				$data=$this->get_by_curl("http://video.zing.vn/player/flowplayer.php?id=".$flow_id[1]);
				preg_match('#<a.*href="(.*?)".*style="(.*?)".*id="player">#s',$data,$flv);
				$url=$flv[1];
				*/
			}
			$pat_mega='#http:\/\/www.megavideo.com\/\?v=(.*?)#';
			if(preg_match($pat_mega, $url)){
				
				//preg_match_all('/[^=]*/',$url,$match);
				/*
				$megavideo_id = $match[0][2];
				$en_id=base64_encode($megavideo_id);
				$arr_server=array("data_movie_server","data_movie","data_movie_server2");
				$ser=$arr_server[rand(0,count($arr_server)-1)];
				$url=$conf['web_url'].'/'.$ser.'/'.$en_id.'.flv';
				*/
				$data=$this->get_by_curl($url);
				preg_match('#<param name=[\'"]movie[\'"] value=[\'"](.*?)[\'"]>#',$data,$param);
				$url=$param[1];
			}
			
			$pat_google='#http:\/\/video\.google\.com\/googleplayer\.swf\?doc[iI]d\=(.*?)#';					
			$pat_google_2='#http:\/\/video\.google\.com\/videoplay\?docid=(.*?)#';
			if(preg_match($pat_google, $url) || preg_match($pat_google_2, $url)){
				$id=explode('=',$url);
				$url=$conf['web_url']."/ggvideo/".$id[1].".flv";
				/*
				$url_get='http://video.google.com/videoplay?docid='.$id[1];
				$data=$this->get_by_curl($url_get);
			//	preg_match("#\'http://vp.video.google.com/videodownload\?(.*?)\'\,#",$data,$r);
			//	$url='http://vp.video.google.com/videodownload?'.$r[1];
				$parse=explode("googleplayer.swf?videoUrl",$data);
				$parse=explode("thumbnailUrl",$parse[1]);
				$google=urldecode($parse[0]);
				$google=str_replace('\x2F','/',$google);
				$google=str_replace('\x3d','',$google);
				$google=str_replace('\x26','',$google);
				$url=$google;
			//	$url=str_replace('\x2F','/',$url);
				//$url=str_replace('\x3d','=',$url);
				//$url=str_replace('\x26','&',$url);
				//$url=urldecode($url);
				
				*/
			}
			
			$pattern_clip1 = '#http:\/\/clip.vn\/watch\/(.*?)\/([^,]+)#';
			$pattern_clip2 = '#http:\/\/clip.vn\/w\/([^,]+),#';
			$pattern_clip3 = '#http:\/\/clip.vn\/watch\/([^,]+)#';
			if(preg_match($pattern_clip1, $url) || preg_match($pattern_clip2, $url) || preg_match($pattern_clip3, $url)){
				if(preg_match($pattern_clip1, $url, $id_sr))
					$id = $id_sr[2];
				elseif(preg_match($pattern_clip2, $url, $id_sr))
					$id = $id_sr[1];
				elseif(preg_match($pattern_clip3, $url)){
					$id_sr=explode(",",$url);
					$id = $id_sr[1];
				}
					if(!$direct)
						$url="http://clip.vn/swf/player.vn.swf?v=3.188&id={$id}&a&enablejs=true&h=http://clip.vn";
					else{
						$link='http://clip.vn/movies/nfo/'.$id;
						$refer="http://static.clip.vn/swf/player.vn.swf?v=3.174&id={$id}&a&enablejs=true&h=http://clip.vn";
						$code=$this->get_by_curl_refer($link,$refer);
						preg_match_all("#<enclosure url='(.*?)'#",$code,$r);
						$url=$r[1][0];							
					}
			}
			
			$pat_blog_com_vn='#http://blog.com.vn/(.*?)#';
			if(preg_match($pat_blog_com_vn, $url)){
				$s = explode('_',$url);
				$s1=explode(".html",$s[1]);
				$link='http://blog.com.vn/home/relatemovie.ashx?videoid='.$s1[0];
				$data=$this->get_by_curl($link);
				preg_match('#<path3>(.*?)</path3>#',$data,$flv_512);
				preg_match('@^(?:http://)?([^/]+)@i',$flv_512[1], $host);
				$url=str_replace($host[1],"video.blog.com.vn",$flv_512[1]);
			}
			
			elseif(preg_match("/http:\/\/(www\.)?dailymotion\.com\/(.*?)/iU", $url)) {			
				if(preg_match("/swf\/(.*?)/iU", $url,$sub))
					$id=$sub[1];
				else{
					preg_match("/video\/(.*?)/iU", $url,$sub);
					$id=$sub[1];
				}
				if($direct)
					$url="http://namdinh.org/media/daily/".$id.".flv";
				else{
					$url="http://www.dailymotion.com/swf/".$id;
					}
			}
			elseif(preg_match('#http://video.timnhanh.com/(.*?)#',$url) || preg_match('#http://video.yume.vn/(.*?)#',$url)){
				
				if($direct){
					$refer="http://static.timnhanh.com/yumevideo/flash_player/simplePlayer.swf";
					$data=$this->get_by_curl($url);
					preg_match("#Set-Cookie:(.*?)\\n#s",$data, $cook);
					preg_match("#var strMemberVideo 	\= '(.*?)'#",$data,$xml);
					$link_xml="http://video.yume.vn/playlist/".$xml[1].".xml";
					//$re=$this->getlink("video.yume.vn",$link_xml,$cook[1]);
					$res=$this->get_by_curl($link_xml);
					preg_match('#urlFLV="(.*?)"#',$res,$flv);
					$url=trim($flv[1]);
				}
				else{

					//$url=$conf['web_url']."/tnhvideo/".base64_encode($url).".flv";
					//$cokk=$this->getCookie("video.timnhanh.com",$url);
					//$data=$this->getlink("video.timnhanh.com",$url,$cokk);
					
					$refer="http://static.timnhanh.com/yumevideo/flash_player/simplePlayer.swf";
					$data=$this->get_by_curl($url);
					preg_match("#Set-Cookie:(.*?)\\n#s",$data, $cook);
					preg_match("#var strMemberVideo 	\= '(.*?)'#",$data,$xml);
					$link_xml="http://video.yume.vn/playlist/".$xml[1].".xml";
					$res=$this->get_by_curl($link_xml);
					preg_match('#urlFLV="(.*?)"#',$res,$flv);
					//$arr=$this->get_head_curl($flv[1]);
					
					//preg_match("#Location:(.*?)\\n#s",$arr, $link);
					//$link=explode('Location: ',$arr[7]);
					$url=trim($flv[1]);
					
					//$url=$link_xml;
				}
			}
			
			elseif (strstr($url,"chacha.vn")){
				$id=explode('/song/',$url);
			//	$data=$this->get_by_curl_not_header('http://r0.6te.net/chacha.php?id='.$id[1]);
				//preg_match("#<daica>(.*?)</daica>#",$data,$url_cc);
				
				//$url="http://chacha.vn/song/getUrl2Download/".$id[1]."#.mp3";
			//	$url=$this->get_by_curl_not_header('http://chacha.vn/song/getUrl?id='.$id[1].'&songTable=1');
				//if(!$url)
					$url="http://chacha.vn/song/getUrl2Download/".$id[1]."#.mp3";
			}
			elseif(preg_match('/youtube.com/i',$url)){
				if(preg_match('/gdata.youtube.com/i',$url)){
					$id=explode('/playlists/',$url);
					$ht=date("dth");
					$utube=$ht.$id[1];
					if($direct)
						$url=$conf['web_url']."/source/down_utube.php?id=".base64_encode($id[1]);
					else
						$url=$conf['web_url']."/source/xml_youtube.php?id=".base64_encode($utube);
				}
				else{
					$videoid=explode('?v=',$url);
					if($videoid[1]==""){
						$videoid=explode('/v/',$url);
									
					}
						$cut=explode("&",$videoid[1]);
						if($cut[1]!="")
							$videoid[1]=$cut[0];
					$url="http://www.youtube.com/?v=".$videoid[1];		
					//$url=$conf['web_url']."/ytbvideo/".$videoid[1].".flv";
					
					$data=$this->get_by_curl($url);
					preg_match('# "t": "(.*?)"#', $data, $t_mat);
					$video = 'http://www.youtube.com/get_video?video_id='.$videoid[1].'&t='.$t_mat[1].'&el=detailpage&ps=&fmt=5';
					$flv=$this->get_head_curl($video);
					preg_match("#Location:(.*?)\\n#s",$flv, $cut);
					$url=trim($cut[1]);
					
					/*
					$xml=$this->get_by_curl_not_header("http://174.129.106.47/RO/ser_grab.php?id=".$videoid[1]."&type=ytb");
					preg_match("#<solo>(.*?)</solo>#s",$xml, $dr);
					$url=$dr[1];
					*/
				}
			}
			elseif(preg_match('/60s.com.vn/i',$url)){
				$data=$this->get_by_curl($url);
				$user_agent="Media-Player";
				preg_match('#<param name=FileName value=(.*?)>#',$data,$wpl);
				$wpl[1]=preg_replace(array('/"/',"/'/"),array('',''),$wpl[1]);
				if($direct){
					$mms=$this->get_by_curl($wpl[1],'','',$user_agent);
					preg_match('#<media src=[\'"](.*?)[\'"] \/>#i',$mms,$wmv);
					$url=$wmv[1];
				}
				else
					$url=$wpl[1];
			}
			elseif(preg_match('/youku.com/i',$url)){
				if(!$direct){
					$videoid=explode('id_',$url);
					$videoid=explode('.html',$videoid[1]);
					$url="http://static.youku.com/v1.0.0025/v/swf/qplayer.swf?VideoIDS=".$videoid[0];
				}
				else{
					$data=$this->get_by_curl("http://keepvid.com/?url={$url}");
					preg_match('#<a href=[\'"]redirect\?(.*?)[\'"] class=[\'"]link[\'"] target=[\'"]\_blank[\'"]>#',$data,$youku);
					$url=urldecode($youku[1]);
					
				}
			}
			elseif(preg_match('/profile.myspace.com/i',$url) || preg_match('/vids.myspace.com/i',$url)){
					$st=0;
					$vid = $this->get_str($url,"&VideoID=","",$st);
					if(!$vid)
						$vid = $this->get_str($url,"&videoid=","",$st);
					if(!$vid)
						$vid = $this->get_str($url,"&videoid=","&",$st);
					$url_rss = "http://mediaservices.myspace.com/services/rss.ashx?type=video&videoID=".$vid;
					$data=$this->get_by_curl($url_rss);
					$url=$this->get_str($data,"<media:content url=\"","\"",$st);
			}
			elseif(preg_match('/nhaccuatui.com/i',$url)){
					$id=explode('=',$url);
					$head=$this->get_head_curl('http://www.nhaccuatui.com/m2/'.$id[1]);
					preg_match("#Location:(.*?)\\n#s",$head, $cut);
					$get=explode('file=',trim($cut[1]));
					$code=$this->get_by_curl($get[1]);
					$parse=explode('</creator><location>',$code);
					$parse=explode('</location>',$parse[1]);
					$url=$parse[0];
			}
			elseif(preg_match('/cyworld.vn/i',$url)){
				$data=$this->get_by_curl($url);
				preg_match('#s1\.addVariable\(["\']server["\']\,["\'](.*?)["\']\)\;#',$data,$server);
				preg_match('#s1\.addVariable\(["\']file["\']\,["\'](.*?)["\']\)\;#',$data,$file);
				$dir_file=$this->cyworld_decode($file[1]);
				$url="http://".$server[1].$dir_file.$file[1];
				
			}
			elseif(preg_match('/veoh.com/i',$url)){
				$id_sr=explode('permalinkId=',$url);
				if(trim($id_sr[1])=='')
					$id_sr=explode('/videos/',$url);
				if($direct)
					$url="http://grab.haiduongvui.com/veoh/".base64_encode($id_sr[1]).".flv";
				else
					$url="http://grab.haiduongvui.com/veoh/".base64_encode($id_sr[1]).".flv";
				
			}
			elseif(preg_match('/www.yeuamnhac.com/i',$url)){
				if(preg_match("#yeuamnhac\.com\/cbeta\/amnhac\/(.*?)#i",$url)){
						$link=explode('/amnhac/',$url);
						$id=explode("/",$link[1]);
						$yan_id=$id[0];
						$code=$this->get_by_curl("http://www.yeuamnhac.com/cbeta/music_details.php?id=".$yan_id);
				}
				else
					$code=$this->get_by_curl($url);
				preg_match('#so\.addVariable\("xml"\, "(.*?)"\)\;#',$code,$link_xml);
				$xml=$this->get_by_curl($link_xml[1]);
				preg_match('#<x src="(.*?)"#',$xml,$dr_url);
				$url=$dr_url[1];
			}
			
			
	return $url;
	}


function get_by_curl($url,$post='',$vars='',$user_agent=''){
	if(!$user_agent) $user_agent="User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6";
    $ch = curl_init(); 
    curl_setopt ($ch, CURLOPT_URL, $url); 
    curl_setopt ($ch, CURLOPT_USERAGENT, $user_agent);  
if($post){
	curl_setopt ($ch , CURLOPT_POST , 1) ; 
	curl_setopt ($ch, CURLOPT_POSTFIELDS, $vars); 
}
    curl_setopt ($ch, CURLOPT_HEADER, 1);

	curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt ($ch, CURLOPT_TIMEOUT, 120);
    $result = curl_exec ($ch);
    curl_close($ch);
return $result;
}

function get_by_curl_refer($url,$refer){
    $ch = curl_init(); 
    curl_setopt ($ch, CURLOPT_URL, $url); 
    curl_setopt ($ch, CURLOPT_USERAGENT, "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");  
	curl_setopt($ch, CURLOPT_REFERER, $refer);
    curl_setopt ($ch, CURLOPT_HEADER, 1);
	curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
    //curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt ($ch, CURLOPT_TIMEOUT, 120);
    $result = curl_exec ($ch);
    curl_close($ch);
return $result;
}

function get_by_curl_not_header($url){
     $ch = curl_init(); 
     curl_setopt ($ch, CURLOPT_URL, $url); 
     curl_setopt ($ch, CURLOPT_USERAGENT, "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6"); 
     curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
     curl_setopt ($ch, CURLOPT_TIMEOUT, 120);
     $result = curl_exec ($ch);
     curl_close($ch);

return $result;
}
	
function get_head_curl($url,$time=10){
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt ($ch, CURLOPT_USERAGENT, "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6"); 
curl_setopt($ch, CURLOPT_REFERER, "http://www.google.com/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT,$time);

$r = curl_exec($ch);

return $r;
}


function get_dm($url){
$arr=$this->get_head_curl($url,10);
$dr=explode('Location: ',$arr);
$dr=explode('Server',$dr[1]);
return $dr[0];
}

function img_resize( $tmpname, $sizew,$sizeh, $save_dir, $save_name )
    {
    $save_dir .= ( substr($save_dir,-1) != "/") ? "/" : "";
        $gis       = getimagesize($tmpname);
    $type       = $gis[2];
    switch($type)
        {
        case "1": $imorig = imagecreatefromgif($tmpname); break;
        case "2": $imorig = imagecreatefromjpeg($tmpname);break;
        case "3": $imorig = imagecreatefrompng($tmpname); break;
        default:  $imorig = imagecreatefromjpeg($tmpname);
        }

        $x = imageSX($imorig);
        $y = imageSY($imorig);

        if(($gis[0] <= $sizew) && ($gis[1] <=$sizeh))
        {
        $av = $x;
        $ah = $y;
        }
            else
        {
			  $av=$sizew;
			  $ah=$sizeh;

        }   
        $im = imagecreate($av, $ah);
        $im = imagecreatetruecolor($av,$ah);
    if (imagecopyresampled($im,$imorig , 0,0,0,0,$av,$ah,$x,$y))
        if (imagejpeg($im, $save_dir.$save_name))
            return true;
            else
            return false;
}


function del_local_img($type,$id){
	global $DB,$conf;
	if($type=="multimedia"){
		$query = $DB->query("SELECT multi_local_img,multi_type FROM ".$conf['prefix']."multimedia WHERE multi_id IN ({$id})");
		while ($img=$DB->fetch_row($query)) {
			if($img['multi_type']==1){
			  if ( (file_exists("../".$conf['album_img']."/".$img['multi_local_img'])) && (!empty($img['multi_local_img'])) )
				   @unlink("../".$conf['album_img']."/".$img['multi_local_img']);
			 if ( (file_exists("../".$conf['album_thumb']."/".$img['multi_local_img'])) && (!empty($img['multi_local_img'])) )
				   @unlink("../".$conf['album_thumb']."/".$img['multi_local_img']);
			}
			elseif($img['multi_type']==2){
			  if ( (file_exists("../".$conf['root_img']."/".$img['multi_local_img'])) && (!empty($img['multi_local_img'])) )
				   @unlink("../".$conf['root_img']."/".$img['multi_local_img']);
			 if ( (file_exists("../".$conf['img_thumb']."/".$img['multi_local_img'])) && (!empty($img['multi_local_img'])) )
				   @unlink("../".$conf['img_thumb']."/".$img['multi_local_img']);
			}
		}
	}
	elseif($type=="singer"){
	$query = $DB->query("SELECT singer_local_img FROM ".$conf['prefix']."singer WHERE singer_id IN ({$id})");
		while ($img=$DB->fetch_row($query)) {
			  if ( (file_exists("../".$conf['singer_img']."/".$img['singer_local_img'])) && (!empty($img['singer_local_img'])) )
				   @unlink("../".$conf['singer_img']."/".$img['singer_local_img']);
		}
	}	
	elseif($type=="playlist"){
		$query = $DB->query("SELECT pl_img FROM ".$conf['prefix']."playlist WHERE pl_id IN ({$id})");
		while ($img=$DB->fetch_row($query)) {
		 if ( (file_exists($conf['dir_imgpl']."/".$img['pl_img'])) && (!empty($img['pl_img'])) )
			@unlink($conf['dir_imgpl']."/".$img['pl_img']);
		}
	}
	elseif($type=="avatar"){
		$qre = $DB->query("SELECT u_avatar FROM ".$conf['prefix']."user WHERE u_id='{$id}'");
		while ($img=$DB->fetch_row($qre)) {
		 if ( (file_exists($conf['dir_avatar']."/".$img['u_avatar'])) && (!empty($img['u_avatar'])) )
			@unlink($conf['dir_avatar']."/".$img['u_avatar']);
		}
	}
	elseif($type=="focus_img"){
		$qre = $DB->query("SELECT focus_img FROM ".$conf['prefix']."focus WHERE focus_id IN ({$id})");
		while ($img=$DB->fetch_row($qre)) {
		 if ( (file_exists("../".$conf['focus_img']."/".$img['focus_img'])) && (!empty($img['focus_img'])) )
			@unlink("../".$conf['focus_img']."/".$img['focus_img']);
		 if ( (file_exists("../".$conf['focus_thumb']."/".$img['focus_img'])) && (!empty($img['focus_img'])) )
				   @unlink("../".$conf['focus_thumb']."/".$img['focus_img']);
		}
	}
}

function build_mail_header($to_email, $from_email) {
	$CRLF = "\n";
	$headers = 'MIME-Version: 1.0'.$CRLF;
	$headers .= 'Content-Type: text/html; charset=UTF-8'.$CRLF;
	$headers .= 'Date: ' . gmdate('D, d M Y H:i:s Z', NOW) . $CRLF;
	$headers .= 'From: <'. $from_email .'>'. $CRLF;
	$headers .= 'Reply-To: <'. $from_email .'>'. $CRLF;
	$headers .= 'Auto-Submitted: auto-generated'. $CRLF;
	$headers .= 'Return-Path: <'. $from_email .'>'. $CRLF;
	$headers .= 'X-Sender: <'. $from_email .'>'. $CRLF; 
	$headers .= 'X-Priority: 3'. $CRLF;
	$headers .= 'X-MSMail-Priority: Normal'. $CRLF;
	$headers .= 'X-MimeOLE: Produced By xtreMedia'. $CRLF;
	$headers .= 'X-Mailer: PHP/ '. phpversion() . $CRLF;
	return $headers;
}

function bad_words($str) {
	$chars = array('lol','dis','dit','dit me','địt mẹ','dis me','dis mẹ','shit','fuck','LOZ','LON','dizz','DIZZ','loz','ljn','lon','địt','Địt','ĐỊT','đéo','Đéo','ĐÉO','lồn','Lồn','LỒN','cặc','Cặc','CẶC','dái','Dái','DÁI','chó','Chó','CHÓ','Cứt','cứt','CỨT','ỉa','Ỉa','đái','Đái','ỈA');
	foreach ($chars as $key => $arr)
		$str = preg_replace( "/(^|\b)".$arr."(\b|!|\?|\.|,|$)/i", "***", $str ); //replace exact
	return $str;
}

	function getCookie($host,$link) {
		$out  = "GET $link HTTP/1.1\r\n";
		$out .= "Host: ".$host."\r\n";
		$out .= "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5\r\n";
		$out .= "Referer: http://www.google.com/\r\n";
		$out .= "Content-Type: application/x-www-form-urlencoded\r\n";
		$out .= "\r\n";
		if (!$con = @fsockopen($host, 80, $errno, $errstr, 10))
			return $errstr." ".$errno;	
		fwrite($con, $out);
		$data = '';
		while (!feof($con)) {
			$data .= fgets($con, 512);
		}
		fclose($con);
	preg_match("#Set-Cookie:(.*?)\\n#s",$data, $res);
		return $res[1];
	}
	function getlink($host,$link,$cookie) {
		$out  = "POST $link HTTP/1.1\r\n";
		$out .= "Host: ".$host."\r\n";
		$out .= "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5\r\n";
		$out .= "Referer: http://www.google.com/\r\n";	
		$out .= "Cookie: $cookie\r\n";
		$out .= "Connection: Close\r\n\r\n";
		
		if (!$con = @fsockopen($host, 80, $errno, $errstr, 10))
			return $errstr." ".$errno;	
		fwrite($con, $out);
		$data = '';
		while (!feof($con)) {
			$data .= fgets($con, 512);
		}	
		fclose($con);
		return $data;
	}
	function get_str($s,$find1,$find2,&$start){ 
		if($start>strlen($s)) return false;
		$pos = strpos($s,$find1,$start);
		if($pos>0){
			$pos += strlen($find1);
			if($find2=="")
				$posend = strlen($s);
			else
				$posend = strpos($s,$find2,$pos);
			if($posend==0) return false;
			$start = $posend;
			return substr($s,$pos,$posend-$pos);
		}
		else
			return false;
	}
	function get_curl_cook($link){
		$user_agent = "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6";
		$ch = curl_init();     
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
		curl_setopt($ch, CURLOPT_URL, $link);
		curl_setopt ($ch, CURLOPT_USERAGENT, $user_agent); 
		curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
		curl_setopt ($ch, CURLOPT_COOKIEJAR, 'cook.txt');
		ob_start();     
		curl_exec ($ch);
		ob_end_clean(); 
		curl_close ($ch);
		unset($ch);
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
		curl_setopt ($ch, CURLOPT_USERAGENT, $user_agent); 
		curl_setopt($ch, CURLOPT_COOKIEFILE, "cook.txt");
		curl_setopt($ch, CURLOPT_URL,$link);
		$result = curl_exec ($ch);
		curl_close ($ch);
		return $result; 
	}
	function cyworld_decode($file){
		$loc6=split("_",$file);
		$loc5=substr($loc6[0],0,strlen($loc6[0])-6);
		$loc8=date("n",$loc5);
		$loc3=$loc8;
		if(strlen($loc3)<2)
			$loc3="0".$loc3;
		$loso=getdate($loc5);
		$loc2=$loso['mday'];
		if(strlen($loc2)<2)
			$loc2="0".$loc2;
		$loc9=$loc5%200;
		for($loc1=$loc9;strlen($loc1)<3;$loc1="0".$loc1)
		{
		}
		return "/".date("Y",$loc5)."/".$loc3."/".$loc2."/".$loc1."/";
	}
	
	function Get_player_epi($movie_id,$epi_id){
		global $conf,$DB;
		$repi=$DB->query("SELECT * FROM ".$conf['prefix']."media where m_id={$epi_id} and m_multimedia={$movie_id}");
	  if($epi=$DB->fetch_row($repi)){
		  $re=$DB->query("SELECT * FROM ".$conf['prefix']."player where player_id={$epi['m_type']}");
		  $type=$DB->fetch_row($re);
		if($type['player_use_xml'])  
   		 $url_file=$conf['web_url'].'/%3Fact=xml%26id='.$epi_id."%26type=2";
		elseif($type['player_use_wpl'])  
   		 $url_file=$conf['web_url'].'/%3Fact=wpl%26id='.$epi_id."%26type=2";
		else
		 $url_file=($type['player_isgrab'])?$this->grab_link($this->unhtmlchars($epi['m_url'])):$this->unhtmlchars($epi['m_url']); 
			$tamtay="/tamtay.php?id=".$epi_id;
			$player=$this->unhtmlchars(stripslashes($type['player_html']));
			$player=str_replace("{WEB_URL}",$conf['web_url']."/",$player);
			$player=str_replace("{WIDTH}",$type['player_width'],$player);
			$player=str_replace("{HEIGHT}",$type['player_height'],$player);
			$player=str_replace("{URL}",$url_file,$player);
			$player=str_replace("{ID_TT}",$tamtay,$player);
			$player=str_replace("{MOVIE_ID}",$movie_id,$player);
	  }
	  return $player;
	}

	 function get_curl($url,$head=1,$nobody=0){
		 $ch = curl_init(); 
		 curl_setopt ($ch, CURLOPT_URL, $url); 
		 curl_setopt ($ch, CURLOPT_USERAGENT, "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6"); 
		 curl_setopt ($ch, CURLOPT_HEADER, $head); 
			curl_setopt($ch, CURLOPT_NOBODY, $nobody);
		 curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
		 curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
		 curl_setopt ($ch, CURLOPT_TIMEOUT, 30);
		 $result = curl_exec ($ch);
		 curl_close($ch);
	
		return $result;
	}
}
?>
